<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH.'libraries/facebook/facebook.php';
class Participate extends CI_Controller {
  var $user_id;
  public function __construct(){
    parent::__construct();
    // $this->output->enable_profiler(TRUE);
    global $facebook;

    $uid = $facebook->getUser();
    if(!$uid) {
      $dialog_url= "https://www.facebook.com/dialog/oauth?"
        . "client_id=" . FB_APP_ID
        . "&redirect_uri=" . urlencode(FB_APP_URL . '&app_data=participate,index')
        . "&scope=";
      exit("<script> top.location.href='" . $dialog_url . "'</script>");
    }
    /***************************************/
    $this->load->model('Users_model');
    //$this->session->set_userdata(array('user_id' => $user_id));
    $this->user_id = $uid;
  }

	public function index()
	{
	  $this->load->helper('form');
    $this->load->library('form_validation');

    $existing_user = $this->Users_model->get_avatar($this->user_id);
    if($existing_user) {
      $this->load->view('header');
      $this->load->view('personal_avatar', array('user_data' => $existing_user, 'first_parts' => first_part_sentences()));
      $this->load->view('footer');
      return;
    }

    $this->form_validation->set_rules('first_name', 'lang:form_first_name_label', 'trim|required|xss_clean|min_length[2]|max_length[50]');
    $this->form_validation->set_rules('last_name', 'lang:form_last_name_label', 'trim|required|xss_clean|min_length[2]|max_length[50]');
    $this->form_validation->set_rules('email', 'lang:form_email_label', 'trim|required|valid_email|xss_clean|min_length[2]|max_length[50]');
    $this->form_validation->set_rules('agree_years', 'lang:agree_years_label', 'required');
    $this->form_validation->set_rules('agree_tos', 'lang:agree_tos_label', 'required');
    $this->form_validation->set_rules('body_style', 'lang:body_style_label', 'is_numeric|less_than[3]|greater_than[0]');
    $this->form_validation->set_rules('first_part_sentence', 'lang:first_part_sentence_label', 'required');
    $this->form_validation->set_rules('personal_message', 'lang:personal_message_label', 'required|max_length[140]');
    // @todo check all validations are set
    $this->form_validation->set_error_delimiters('<span class="error">', '</span><br />');

    if ($this->form_validation->run() == FALSE) // validation hasn't been passed
    {
      $this->load->view('header');
      $this->load->view('participation_form', array('form_fields' => $this->_form_fields(), 'body_parts' => $this->_body_parts()));
      $this->load->view('footer');
    }
    else // passed validation proceed to post success logic
    {
      // save the image
      $filename  = $this->_build_avatar();

      // build array for the model
      $form_data = array(
        'user_id' => $this->user_id,
        'first_name' => set_value('first_name'),
        'last_name' => set_value('last_name'),
        'email' => set_value('email'),
        'filename' => $filename,
        'first_part_sentence' => $this->input->post('first_part_sentence'),
        'personal_message' => set_value('personal_message'),
        'avatar_data' => (int)($this->input->post('body_style') . $this->input->post('back_img') . $this->input->post('body_img') . $this->input->post('eyes_img') . $this->input->post('hair_img') . $this->input->post('mouth_img')),
        'timestamp' => time(),
      );

      // run insert model to write data to db
      if ($filename && !$this->Users_model->get_avatar($this->user_id) && $this->Users_model->insert_entry($form_data) == TRUE) // the information has therefore been successfully saved in the db
      {
        $existing_user = $this->Users_model->get_avatar($this->user_id);
        $this->load->view('header');
        $this->load->view('personal_avatar', array('user_data' => $existing_user, 'first_parts' => first_part_sentences()));
        $this->load->view('footer');
      }
      else
      {
        echo 'An error occurred saving your information. Please try again later';
        // Or whatever error handling is necessary
      }
    }
  }

  public function restart() {
    $existing_user = $this->Users_model->get_avatar($this->user_id);
    if($existing_user->status == 2) {
      $this->Users_model->drop_avatar($existing_user->id);
    }
    redirect('participate/index');
  }

	function _form_fields() {
	  return array(
	    'first_name' => array(
	      'name'        => 'first_name',
        'id'          => 'first_name',
        'value'       => set_value('first_name'),
        'maxlength'   => '50',
        'size'        => '50',
        'style'       => 'width:50%',
	    ),
	    'last_name' => array(
	      'name'        => 'last_name',
        'id'          => 'last_name',
        'value'       => set_value('last_name'),
        'maxlength'   => '50',
        'size'        => '50',
        'style'       => '', // example: 'width:50%',
	    ),
	    'email' => array(
	      'name'        => 'email',
        'id'          => 'email',
        'value'       => set_value('email'),
        'maxlength'   => '50',
        'size'        => '50',
        'style'       => '',
	    ),
	    'agree_years' => array(
        'name'        => 'agree_years',
        'id'          => 'agree_years',
        'value'       => 'checked',
        'checked'     => FALSE,
        'style'       => 'margin:10px',
      ),
	    'agree_tos' => array(
        'name'        => 'agree_tos',
        'id'          => 'agree_tos',
        'value'       => 'checked',
        'checked'     => FALSE,
        'style'       => 'margin:10px',
      ),
	    'images' => array(
	      'back_img'   => isset($_POST['back_img']) ? $_POST['back_img'] : 1,
	      'body_style' => isset($_POST['body_style']) ? $_POST['body_style'] : 0,
	      'body_img'   => isset($_POST['body_img']) ? $_POST['body_img'] : 1,
	      'eyes_img'   => isset($_POST['eyes_img']) ? $_POST['eyes_img'] : 1,
	      'hair_img'   => isset($_POST['hair_img']) ? $_POST['hair_img'] : 1,
	      'mouth_img'   => isset($_POST['mouth_img']) ? $_POST['mouth_img'] : 1,
	      'tribune_img'   => 1,
	    ),
	    'first_part_sentence' => first_part_sentences(),
	    'personal_message' => array(
        'name'        => 'personal_message',
        'id'          => 'personal_message',
        'value'       => set_value('personal_message'),
        'rows'        => '5',
        'cols'        => '50',
        'style'       => '',
	      'maxlength'   => '140',
      ),
	  );

	}

	function _body_parts() {
	  return array(
	    'styles' => 2,
	    'back' => 3,
	    'body' => 5,
	    'mouth' => 7,
	    'eyes' => 5,
	    'hair' => 10,
	    'tribune' => 1,
	  );
	}

	function _build_avatar() {
	  $this->load->helper('avatar');
	  //creating a new instance of your shiny new avatar class <img src="http://www.bolducpress.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley">
    $avatar = new avatar;

    //setting the width of your final image (the image will
    //resize themselves dynamically)
    $avatar->set_width(600);

    //setting your background color to black
    $avatar->set_background("#FFFFFF");

    //you can also send it an image
    //$avatar->set_background("my_background_image.png");

    //ah hah! adding your body parts, think of it like layers
    //in photoshop in reverse order.
    $avatar->add_layer('images/avatars/back/back_' . $this->input->post('back_img') . '.png');
    $parts = array('body', 'mouth', 'eyes', 'hair', 'tribune');

    foreach ($parts as $part) {
      if($this->input->post('body_style') == 1) {
        $offset = 205;
      }
      else {
        $offset = -30;
      }
      $avatar->add_layer('images/avatars/' . $part . '/' . $part . '_' . $this->input->post('body_style') . '_' . $this->input->post('' . $part . '_img') . '.png', $offset);
    }

    //you're done setting the width, the background and the
    //layers, let's build this sucker!
    $filename = md5($this->user_id . time()) . '.jpg';
    $avatar->set_filename('uploads/'. $filename);
    if($avatar->build()) {
      $this->_build_tmb($filename);
      return $filename;
    }
    else {
      return FALSE;
    }
	}

function _build_tmb($filename) {
	  $this->load->helper('avatar');
	  //creating a new instance of your shiny new avatar class <img src="http://www.bolducpress.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley">
    $avatar = new avatar;

    //setting the width of your final image (the image will
    //resize themselves dynamically)
    $avatar->set_width(240);

    //setting your background color to black
    $avatar->set_background("#FFFFFF");

    //you can also send it an image
    //$avatar->set_background("my_background_image.png");

    //ah hah! adding your body parts, think of it like layers
    //in photoshop in reverse order.
    $avatar->add_layer('images/avatars/back/back_' . $this->input->post('back_img') . '.png');
    $parts = array('body', 'mouth', 'eyes', 'hair', 'tribune');

    foreach ($parts as $part) {
      $avatar->add_layer('images/avatars/' . $part . '/' . $part . '_' . $this->input->post('body_style') . '_' . $this->input->post('' . $part . '_img') . '.png', 40);
    }
    /*
    $parts = array('back', 'body', 'mouth', 'eyes', 'hair');

    foreach ($parts as $part) {
      $avatar->add_layer('images/avatars/' . $part . '/' . $part . '_' . $this->input->post('body_style') . '_' . $this->input->post('' . $part . '_img') . '.png');
      //$avatar->add_layer('images/avatars/' . $part . '/' . $part . '_' . $this->input->post('body_style') . '_' . $this->input->post('' . $part . '_img') . '.png', 0,0,200);
    }
*/
    //you're done setting the width, the background and the
    //layers, let's build this sucker!
    $avatar->set_filename('uploads/t_'. $filename);
    if($avatar->build()) {
      return $filename;
    }
    else {
      return FALSE;
    }
	}
}